package usercenter

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ AppConfigModel = (*customAppConfigModel)(nil)

type (
	// AppConfigModel is an interface to be customized, add more methods here,
	// and implement the added methods in customAppConfigModel.
	AppConfigModel interface {
		appConfigModel
		Find(ctx context.Context, pageNo, pageSize int64) ([]*AppConfig, error)
		Count(ctx context.Context) (int64, error)
	}

	customAppConfigModel struct {
		*defaultAppConfigModel
	}
)

// NewAppConfigModel returns a model for the database table.
func NewAppConfigModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) AppConfigModel {
	return &customAppConfigModel{
		defaultAppConfigModel: newAppConfigModel(conn, c, opts...),
	}
}

func (m *customAppConfigModel) Find(ctx context.Context, pageNo, pageSize int64) ([]*AppConfig, error) {
	if pageNo < 1 {
		pageNo = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}
	resp := make([]*AppConfig, 0)
	query := fmt.Sprintf("select %s from %s order by app_version desc limit ? offset ?", appConfigRows, m.table)
	err := m.QueryRowsNoCacheCtx(ctx, &resp, query, pageSize, (pageNo-1)*pageSize)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *customAppConfigModel) Count(ctx context.Context) (int64, error) {
	var count int64
	query := fmt.Sprintf("select count(app_version) from %s", m.table)
	err := m.QueryRowNoCacheCtx(ctx, &count, query)
	switch err {
	case nil:
		return count, nil
	default:
		return 0, err
	}
}
